/*
 * Copyright (c) 2012 Google Inc.
 *
 * All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse
 * Public License v1.0 which accompanies this distribution, and is available at
 *
 * http://www.eclipse.org/legal/epl-v10.html
 */
package com.google.eclipse.terminal.local.ui.command;

import static com.google.eclipse.terminal.local.ui.view.TerminalView.openTerminalView;

import java.io.File;
import java.io.IOException;
import java.net.URI;

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.Path;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IURIEditorInput;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.handlers.HandlerUtil;

import com.google.eclipse.terminal.local.Activator;

/**
 * @author alruiz@google.com (Alex Ruiz)
 */
public class OpenTerminalCommand extends AbstractHandler {

  @Override public Object execute(final ExecutionEvent event) {
    IPath path = null;
    final IWorkbenchPart part = HandlerUtil.getActivePart(event);
    if (part instanceof IEditorPart) {
       final IEditorInput input = ((IEditorPart) part).getEditorInput();
       if (input instanceof IURIEditorInput) {
          final URI uri = ((IURIEditorInput) input).getURI();
          if ("file".equals(uri.getScheme())) {
             File file = new File(uri);
             if (file.isFile()) {
                file = file.getParentFile();
             }
             if (file.isDirectory()) {
                try {
                   path = new Path(file.getCanonicalPath());
                } catch (final IOException e) {
                   Activator.log(String.format("Failed to resolve path %s", uri), e);
                }
             }
          }
       }
    } else {
       final ISelection selection = HandlerUtil.getCurrentSelection(event);
       IResource target = resourceFrom(selection);
       if (target != null) {
          if (!(target instanceof IContainer)) {
             target = target.getParent();
          }
          path = target.getLocation();
       }
    }
    openTerminalView(path);
    return null;
  }

  private IResource resourceFrom(final ISelection selection) {
    if (!(selection instanceof IStructuredSelection)) {
      return null;
    }
    final Object o = ((IStructuredSelection) selection).getFirstElement();
    if (!(o instanceof IAdaptable)) {
      return null;
    }
    return (IResource) ((IAdaptable) o).getAdapter(IResource.class);
  }
}
